<script>
import { codemirror, CodeMirror } from 'vue-codemirror'
import 'codemirror/mode/sql/sql.js'; // SQL mode for syntax highlighting
import 'codemirror/lib/codemirror.css'
import { filterObj } from '@/utils/util'
import { postAction } from '@api/manage'
import JCodeEditor from '@/components/jeecg/JCodeEditor'
export default ({
  components: { codemirror,JCodeEditor },
  data(){
    return {
      title: "即席查询",
      width:1600,
      visible: false,
      dataSource:[],
      columns:[],
      sqlCode: '', // 初始SQL代码
      loading:false,
      tableId: '',

      url: {
        jxcx: '/dcloud-platform/api/datalibLogicTable/v1/jxcx',
      }
    }
  },
  methods:{
    handleOk(){
      this.close()
    },
    handleCancel(){
      this.close()
    },
    close () {
      this.visible = false;
    },
    open(record){
      this.clearSearch()
      this.sqlCode = '';
      this.tableId = record.id;
      this.visible = true;
    },
    clearSearch(){
      this.dataSource = [];
      this.columns = [];
    },

    formatSql(){
      this.clearSearch()
      let params = {}
      params['tableId'] = this.tableId;
      params['sql'] = this.sqlCode;
      postAction(this.url.jxcx, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.data
            // 构建 columns 数组
            res.result.keys.forEach(def => {
              let one = {title:def,dataIndex:def}
              this.columns.push(one)
            });
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
})
</script>

<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消">
    <j-code-editor
      language="sql"
      v-model="sqlCode"
      :fullScreen="true"
      style="min-height: 100px"/>
    <button @click="formatSql()">SQL执行</button>
    <a-table
      ref="table"
      :columns="columns"
      :dataSource="dataSource"
      :loading="loading"
      :scroll="{x:true}"
      bordered
      class="j-table-force-nowrap"
      rowKey="id"
      size="middle">

    </a-table>
  </j-modal>

</template>

<style scoped>

</style>